/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.kramerius.fedoraaccess.rest;

import cz.mzk.kramerius.commons.DatastreamId;
import cz.mzk.kramerius.commons.Namespaces;
import cz.mzk.kramerius.fedoraaccess.FedoraServer;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.QName;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
class AddRelationshipFedora3_3Operation extends Fedora3_3Operation {

    public AddRelationshipFedora3_3Operation(FedoraServer fedoraServer) {
        super(fedoraServer);
    }

    boolean run(String subject, String predicate, String predicatePrefix, String object) {
        try {
            Document relsExt = getDatastreamDissemination(subject, DatastreamId.RELS_EXT);
            addRelationship(relsExt, predicate, predicatePrefix, object);
            updateDatastreamInlineContent(subject, DatastreamId.RELS_EXT, relsExt);
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

    private void addRelationship(Document relsExt, String predicate, String predicatePrefix, String object) {
        Element root = (Element) descriptionXpath.selectSingleNode(relsExt);
        Element predicateEl = root.addElement(new QName(predicate, Namespaces.getNamespace(predicatePrefix)));
        predicateEl.addAttribute(new QName("resource", Namespaces.rdf), RDF_PID_PREFIX.concat(object));
    }
}
